<template>
  <div class="user-management">
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户账户</p>
    </div>

    <div class="toolbar">
      <div class="search-box">
        <input v-model="searchQuery" type="text" placeholder="搜索用户..." />
        <button @click="searchUsers" class="btn btn-primary">搜索</button>
      </div>
      <div class="actions">
        <select v-model="roleFilter">
          <option value="">所有角色</option>
          <option value="super_admin">超级管理员</option>
          <option value="teacher">教师</option>
          <option value="student">学生</option>
        </select>
        <button @click="showCreateModal = true" class="btn btn-success">新增用户</button>
      </div>
    </div>

    <div class="user-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>
              <span class="role-badge" :class="user.role">{{ getRoleText(user.role) }}</span>
            </td>
            <td>
              <span class="status-badge" :class="user.status">{{ getStatusText(user.status) }}</span>
            </td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td>
              <div class="action-buttons">
                <button @click="editUser(user)" class="btn btn-sm btn-primary">编辑</button>
                <button @click="showRoleModal(user)" class="btn btn-sm btn-info">分配角色</button>
                <button @click="toggleUserStatus(user)" class="btn btn-sm" :class="user.status === 'active' ? 'btn-warning' : 'btn-success'">
                  {{ user.status === 'active' ? '禁用' : '启用' }}
                </button>
                <button @click="removeUser(user)" class="btn btn-danger">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="btn btn-secondary">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="btn btn-secondary">下一页</button>
    </div>

    <!-- 创建/编辑用户模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '新增用户' : '编辑用户' }}</h3>
          <button @click="closeModals" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label>用户名</label>
              <input v-model="userForm.username" type="text" required />
            </div>
            <div class="form-group">
              <label>姓名</label>
              <input v-model="userForm.name" type="text" required />
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input v-model="userForm.email" type="email" required />
            </div>
            <div class="form-group">
              <label>角色</label>
              <select v-model="userForm.role" required>
                <option value="student">学生</option>
                <option value="teacher">教师</option>
                <option value="super-admin">超级管理员</option>
              </select>
            </div>
            <div v-if="showCreateModal" class="form-group">
              <label>密码</label>
              <input v-model="userForm.password" type="password" required />
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModals" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 角色分配模态框 -->
    <div v-if="showRoleAssignModal" class="modal-overlay" @click="closeRoleModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>分配角色 - {{ currentUser?.name }}</h3>
          <button @click="closeRoleModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="role-assignment">
            <div class="current-roles">
              <h4>当前角色</h4>
              <div class="role-list">
                <div v-for="role in userRoles" :key="role.id" class="role-item">
                  <span class="role-name">{{ role.name }}</span>
                  <button @click="removeUserRole(role.id)" class="btn btn-sm btn-danger">移除</button>
                </div>
                <div v-if="userRoles.length === 0" class="no-roles">暂无角色</div>
              </div>
            </div>
            <div class="available-roles">
              <h4>可分配角色</h4>
              <div class="role-list">
                <div v-for="role in availableRoles" :key="role.id" class="role-item">
                  <span class="role-name">{{ role.name }}</span>
                  <span class="role-desc">{{ role.description }}</span>
                  <button @click="assignUserRole(role.id)" class="btn btn-sm btn-success">分配</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeRoleModal" class="btn btn-secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { getUsers, createUser, updateUser, deleteUser, getRoles, getUserRoles, assignRoleToUser, removeRoleFromUser } from '@/api/rbac/rbac'
import { getUsersByRoleName, getTeachers, getStudents, getSuperAdmins } from '@/api/rbac/usersByRole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/stores'

export default {
  name: 'UserManagement',
  setup() {
    const appStore = useAppStore()
    const searchQuery = ref('')
    const roleFilter = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const showRoleAssignModal = ref(false)
    const currentUser = ref(null)
    const userRoles = ref([])
    const availableRoles = ref([])
    const allRoles = ref([])
    
    const userForm = ref({
      id: null,
      username: '',
      name: '',
      email: '',
      role: 'student',
      password: ''
    })

    const users = ref([])

    const filteredUsers = computed(() => {
      let filtered = users.value
      
      if (searchQuery.value) {
        filtered = filtered.filter(user => 
          user.username.includes(searchQuery.value) ||
          user.name.includes(searchQuery.value) ||
          user.email.includes(searchQuery.value)
        )
      }
      
      if (roleFilter.value) {
        filtered = filtered.filter(user => user.role === roleFilter.value)
      }
      
      return filtered
    })

    const totalPages = computed(() => {
      return Math.ceil(filteredUsers.value.length / pageSize.value)
    })

    const paginatedUsers = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredUsers.value.slice(start, end)
    })

    const getRoleText = (role) => {
      const roleMap = {
        'super-admin': '超级管理员',
        'teacher': '教师',
        'student': '学生'
      }
      return roleMap[role] || role
    }

    const getStatusText = (status) => {
      return status === 'active' ? '正常' : '禁用'
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    const searchUsers = async () => {
      // 根据角色筛选重新加载用户
      currentPage.value = 1
      if (roleFilter.value) {
        await loadUsers(roleFilter.value)
      } else {
        await loadUsers()
      }
    }

    const changePage = (page) => {
      currentPage.value = page
      // 由于当前使用前端分页，这里不需要重新加载数据
      // 如果将来改为后端分页，可以在这里调用 loadUsers()
    }

    const editUser = (user) => {
      userForm.value = {
        id: user.userId,
        username: user.username,
        name: user.realname || user.username,
        email: user.email,
        role: user.role || 'student',
        password: ''
      }
      showEditModal.value = true
    }

    const toggleUserStatus = (user) => {
      user.status = user.status === 'active' ? 'inactive' : 'active'
    }

    const removeUser = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 ${user.realname || user.username} 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        appStore.setLoading(true)
        await deleteUser(user.userId)
        ElMessage.success('用户删除成功')
        await loadUsers()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除失败，请重试')
        }
      } finally {
        appStore.setLoading(false)
      }
    }

    const saveUser = async () => {
      try {
        appStore.setLoading(true)
        if (showCreateModal.value) {
          // 创建新用户
          const userData = {
            username: userForm.value.username,
            password: userForm.value.password,
            email: userForm.value.email,
            realname: userForm.value.name
          }
          await createUser(userData)
          ElMessage.success('用户创建成功')
        } else {
          // 更新用户
          const userData = {
            username: userForm.value.username,
            email: userForm.value.email,
            realname: userForm.value.name
          }
          await updateUser(userForm.value.id, userData)
          ElMessage.success('用户更新成功')
        }
        await loadUsers()
        closeModals()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        appStore.setLoading(false)
      }
    }

    const closeModals = () => {
      showCreateModal.value = false
      showEditModal.value = false
      userForm.value = {
        id: null,
        username: '',
        name: '',
        email: '',
        role: 'student',
        password: ''
      }
    }

    const loadUsers = async (role = null) => {
      try {
        appStore.setLoading(true)
        let response
        
        if (role) {
          // 根据角色获取用户
          response = await getUsersByRoleName(role)
          if (response.code === 200 && response.data) {
            users.value = response.data.map(user => ({
              ...user,
              id: user.userId,
              name: user.realname || user.username,
              role: role, // 使用传入的角色
              status: 'active', // 默认状态
              createdAt: user.createdAt
            }))
          }
        } else {
          // 获取所有用户
          response = await getUsers()
          if (response.code === 200 && response.data) {
            // 先显示基本用户信息，角色默认为'加载中...'
            users.value = response.data.map(user => ({
              ...user,
              id: user.userId,
              name: user.realname || user.username,
              role: '加载中...',
              status: 'active',
              createdAt: user.createdAt
            }))
            
            // 动态获取每个用户的角色信息
            response.data.forEach(async (user, index) => {
              try {
                const rolesResponse = await getUserRoles(user.userId)
                const userRoles = rolesResponse.code === 200 && rolesResponse.data ? rolesResponse.data : []
                const primaryRole = userRoles.length > 0 ? userRoles[0].roleName : 'student'
                
                // 更新对应用户的角色信息
                if (users.value[index] && users.value[index].id === user.userId) {
                  users.value[index].role = primaryRole
                }
              } catch (error) {
                console.error(`获取用户 ${user.userId} 角色失败:`, error)
                // 更新为默认角色
                if (users.value[index] && users.value[index].id === user.userId) {
                  users.value[index].role = 'student'
                }
              }
            })
          }
        }
      } catch (error) {
        console.error('加载用户数据失败:', error)
        ElMessage.error('加载数据失败，请重试')
      } finally {
        appStore.setLoading(false)
      }
    }

    // 角色分配相关方法
    const loadRoles = async () => {
      try {
        const response = await getRoles()
        if (response.data && response.data.success) {
          allRoles.value = response.data.data || []
        }
      } catch (error) {
        console.error('加载角色数据失败:', error)
        ElMessage.error('加载角色数据失败')
      }
    }

    const showRoleModal = async (user) => {
      currentUser.value = user
      showRoleAssignModal.value = true
      await loadUserRoles(user.id)
      updateAvailableRoles()
    }

    const loadUserRoles = async (userId) => {
      try {
        const response = await getUserRoles(userId)
        if (response.data && response.data.success) {
          userRoles.value = response.data.data || []
        }
      } catch (error) {
        console.error('加载用户角色失败:', error)
        ElMessage.error('加载用户角色失败')
        userRoles.value = []
      }
    }

    const updateAvailableRoles = () => {
      const userRoleIds = userRoles.value.map(role => role.id)
      availableRoles.value = allRoles.value.filter(role => !userRoleIds.includes(role.id))
    }

    const assignUserRole = async (roleId) => {
      try {
        appStore.setLoading(true)
        const response = await assignRoleToUser(currentUser.value.id, roleId)
        if (response.data && response.data.success) {
          ElMessage.success('角色分配成功')
          await loadUserRoles(currentUser.value.id)
          updateAvailableRoles()
        }
      } catch (error) {
        console.error('分配角色失败:', error)
        ElMessage.error('分配角色失败')
      } finally {
        appStore.setLoading(false)
      }
    }

    const removeUserRole = async (roleId) => {
      try {
        await ElMessageBox.confirm(
          '确定要移除该角色吗？',
          '确认移除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        appStore.setLoading(true)
        const response = await removeRoleFromUser(currentUser.value.id, roleId)
        if (response.data && response.data.success) {
          ElMessage.success('角色移除成功')
          await loadUserRoles(currentUser.value.id)
          updateAvailableRoles()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('移除角色失败:', error)
          ElMessage.error('移除角色失败')
        }
      } finally {
        appStore.setLoading(false)
      }
    }

    const closeRoleModal = () => {
      showRoleAssignModal.value = false
      currentUser.value = null
      userRoles.value = []
      availableRoles.value = []
    }

    // 监听角色筛选变化
    watch(roleFilter, async (newRole) => {
      if (newRole) {
        await loadUsers(newRole)
      } else {
        await loadUsers()
      }
    })

    onMounted(() => {
      loadUsers()
      loadRoles()
    })

    return {
      searchQuery,
      roleFilter,
      currentPage,
      totalPages,
      showCreateModal,
      showEditModal,
      showRoleAssignModal,
      currentUser,
      userRoles,
      availableRoles,
      userForm,
      users,
      filteredUsers,
      paginatedUsers,
      getRoleText,
      getStatusText,
      formatDate,
      searchUsers,
      changePage,
      editUser,
      toggleUserStatus,
      removeUser,
      saveUser,
      closeModals,
      loadUsers,
      showRoleModal,
      assignUserRole,
      removeUserRole,
      closeRoleModal
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.actions {
  display: flex;
  gap: 10px;
}

.actions select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  text-decoration: none;
  display: inline-block;
}

.btn-primary { background: #007bff; color: white; }
.btn-success { background: #28a745; color: white; }
.btn-warning { background: #ffc107; color: #212529; }
.btn-danger { background: #dc3545; color: white; }
.btn-secondary { background: #6c757d; color: white; }
.btn-sm { padding: 4px 8px; font-size: 12px; }

.user-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.user-table table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.user-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.role-badge,
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.super-admin { background: #e3f2fd; color: #1976d2; }
.role-badge.teacher { background: #f3e5f5; color: #7b1fa2; }
.role-badge.student { background: #e8f5e8; color: #388e3c; }

.status-badge.active { background: #e8f5e8; color: #388e3c; }
.status-badge.inactive { background: #ffebee; color: #d32f2f; }

.action-buttons {
  display: flex;
  gap: 5px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.role-assignment {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-roles,
.available-roles {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
}

.current-roles h4,
.available-roles h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.role-list {
  max-height: 200px;
  overflow-y: auto;
}

.role-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.role-item:last-child {
  border-bottom: none;
}

.role-name {
  font-weight: 500;
  color: #333;
  margin-right: 10px;
}

.role-desc {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
}

.no-roles {
  padding: 20px;
  text-align: center;
  color: #999;
  font-style: italic;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>